package cn.stylefeng.guns.modular.demo.controller;


import cn.stylefeng.guns.dao.entity.AuditNode;
import cn.stylefeng.guns.dao.service.IAuditNodeService;
import cn.stylefeng.guns.modular.demo.controller.domain.AuditNodeSaveVO;
import cn.stylefeng.guns.modular.demo.controller.domain.AuditNodeVO;
import cn.stylefeng.roses.kernel.rule.annotation.BusinessLog;
import cn.stylefeng.roses.kernel.rule.enums.ResBizTypeEnum;
import cn.stylefeng.roses.kernel.rule.pojo.response.ResponseData;
import cn.stylefeng.roses.kernel.rule.pojo.response.SuccessResponseData;
import cn.stylefeng.roses.kernel.scanner.api.annotation.ApiResource;
import cn.stylefeng.roses.kernel.scanner.api.annotation.PostResource;
import cn.stylefeng.roses.kernel.system.modular.role.entity.SysRole;
import cn.stylefeng.roses.kernel.system.modular.role.service.SysRoleService;
import cn.stylefeng.roses.kernel.system.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.system.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@ApiResource(name = "审批流", resBizType = ResBizTypeEnum.BUSINESS, path = "/audit/set")
public class AuditController {

    @Resource
    private IAuditNodeService auditNodeService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserService sysUserService;



    /**
     * 审批详情
     *
     * @author fengshuonan
     * @since 2021/1/24 10:59
     */
    @PostResource(name = "核销审批设置详情", path = "/detail", requiredLogin = true, requiredPermission = true)
    @ApiOperation("核销审批设置详情")
    public ResponseData<List<AuditNodeVO>> detail() {
        List<AuditNode> auditNodes = auditNodeService.list(Wrappers.<AuditNode>lambdaQuery().eq(AuditNode::getTemplate, "CAV"));
        //节点分组
        Map<Integer, List<AuditNode>> auditNodeMap = auditNodes.stream().collect(Collectors.groupingBy(AuditNode::getNodeOrder));
        Map<String, List<AuditNode>> typeMap = auditNodes.stream().collect(Collectors.groupingBy(AuditNode::getType));

        Map<Long, SysRole> allRoleMap = Maps.newHashMap();
        Map<Long, SysUser> allUserMap = Maps.newHashMap();
        //查询所有角色
        List<AuditNode> roleNodeList = typeMap.get("role");
        if (CollectionUtils.isNotEmpty(roleNodeList)) {
            List<Long> collect = roleNodeList.stream().map(AuditNode::getApproverId).collect(Collectors.toList());
            allRoleMap = sysRoleService.list(Wrappers.<SysRole>lambdaQuery().in(SysRole::getRoleId, collect)).stream().collect(Collectors.toMap(SysRole::getRoleId, Function.identity()));
        }
        //查询所有用户
        List<AuditNode> userNodeList = typeMap.get("user");
        if (CollectionUtils.isNotEmpty(userNodeList)) {
            List<Long> collect = userNodeList.stream().map(AuditNode::getApproverId).collect(Collectors.toList());
            allUserMap = sysUserService.list(Wrappers.<SysUser>lambdaQuery().in(SysUser::getUserId, collect)).stream().collect(Collectors.toMap(SysUser::getUserId, Function.identity()));
        }
        ArrayList<AuditNodeVO> auditNodeVOS = Lists.newArrayList();

        for (Map.Entry<Integer, List<AuditNode>> entry : auditNodeMap.entrySet()) {
            Integer nodeOrder = entry.getKey();
            ArrayList<SysRole> roles = Lists.newArrayList();
            ArrayList<SysUser> users = Lists.newArrayList();
            List<AuditNode> auditNodeList = entry.getValue();
            for (AuditNode auditNode : auditNodeList) {
                String type = auditNode.getType();
                if (Objects.equals(type, "user")) {
                    SysUser sysUser = allUserMap.get(auditNode.getApproverId());
                    if (Objects.nonNull(sysUser)) {
                        users.add(sysUser);
                    }
                } else if (Objects.equals(type, "role")) {
                    SysRole sysRole = allRoleMap.get(auditNode.getApproverId());
                    if (Objects.nonNull(sysRole)) {
                        roles.add(sysRole);
                    }
                }
            }

            AuditNodeVO auditNodeVO = new AuditNodeVO();
            auditNodeVO.setNodeOrder(nodeOrder);
            auditNodeVO.setUsers(users);
            auditNodeVO.setRoles(roles);
            auditNodeVOS.add(auditNodeVO);
        }
        return new SuccessResponseData<>(auditNodeVOS);
    }

    /**
     * 审批详情
     *
     * @author fengshuonan
     * @since 2021/1/24 10:59
     */
    @PostResource(name = "核销审批设置保存", path = "/save", requiredLogin = true, requiredPermission = true)
    @ApiOperation("核销审批设置保存")
    @BusinessLog
    public ResponseData<Boolean> save(@RequestBody AuditNodeSaveVO auditNodeSaveVO) {
        List<AuditNodeSaveVO.AuditNodeSaveNodeVO> nodeList = auditNodeSaveVO.getNodeList();
        //先删除
        auditNodeService.remove(Wrappers.<AuditNode>lambdaQuery().eq(AuditNode::getTemplate, "CAV"));

        List<AuditNode> collect = nodeList.stream().flatMap(r -> {
            ArrayList<AuditNode> all = Lists.newArrayList();
            Integer nodeOrder = r.getNodeOrder();
            List<Long> userIdList = r.getUserIdList();
            List<Long> roleIdList = r.getRoleIdList();
            if (CollectionUtils.isNotEmpty(userIdList)) {
                List<AuditNode> auditNodes = userIdList.stream().map(z -> {
                    AuditNode auditNode = new AuditNode();
                    auditNode.setType("user");
                    auditNode.setNodeOrder(nodeOrder);
                    auditNode.setTemplate("CAV");
                    auditNode.setApproverId(z);
                    return auditNode;
                }).collect(Collectors.toList());
                all.addAll(auditNodes);
            }

            if (CollectionUtils.isNotEmpty(roleIdList)) {
                List<AuditNode> auditNodes = roleIdList.stream().map(z -> {
                    AuditNode auditNode = new AuditNode();
                    auditNode.setType("role");
                    auditNode.setNodeOrder(nodeOrder);
                    auditNode.setTemplate("CAV");
                    auditNode.setApproverId(z);
                    return auditNode;
                }).collect(Collectors.toList());
                all.addAll(auditNodes);
            }
            return all.stream();
        }).collect(Collectors.toList());
        auditNodeService.saveBatch(collect);
        return new SuccessResponseData<>(true);
    }





}
